<template>
  <div class="login-bg">
    <el-row justify="center" align="middle" class="login-row">
      <el-col :xs="22" :sm="16" :md="10" :lg="8" :xl="6">
        <el-card class="login-card" shadow="always">
          <div class="login-header">
            <el-icon size="48" color="#409EFF"><UserFilled /></el-icon>
            <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
            <el-divider />
          </div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" label-position="left" @submit.prevent="handleSubmit">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" clearable size="large" :input-style="inputStyle" />
            </el-form-item>
            <el-form-item v-if="!isLogin" label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" clearable size="large" :input-style="inputStyle" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password clearable size="large" :input-style="inputStyle" />
            </el-form-item>
            <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" show-password clearable size="large" :input-style="inputStyle" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleSubmit" size="large" style="width:100%; border-radius: 24px;">
                {{ isLogin ? '登录' : '注册' }}
              </el-button>
            </el-form-item>
          </el-form>
          <div class="login-footer">
            <span v-if="isLogin">还没有账户？<el-link type="primary" @click="toggleMode">立即注册</el-link></span>
            <span v-else>已有账户？<el-link type="primary" @click="toggleMode">立即登录</el-link></span>
          </div>
          <el-alert v-if="message" :title="message" :type="messageType" show-icon style="margin-top: 16px;" :closable="false" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'

const router = useRouter()
const isLogin = ref(true)
const loading = ref(false)
const message = ref('')
const messageType = ref('')
const formRef = ref(null)

const inputStyle = {
  '::placeholder': {
    color: '#bfbfbf',
    fontSize: '15px'
  }
}

const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: (rule, value) => value === form.password, message: '两次输入的密码不一致', trigger: 'blur' }
  ]
}

const API_BASE_URL = 'http://localhost:3001/api'

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      if (isLogin.value) {
        // 登录
        const response = await fetch(`${API_BASE_URL}/login`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username: form.username, password: form.password })
        })
        const data = await response.json()
        if (response.ok) {
          localStorage.setItem('token', data.token)
          localStorage.setItem('user', JSON.stringify(data.user))
          ElMessage.success('登录成功')
          router.push('/home')
        } else {
          message.value = data.error || '登录失败'
          messageType.value = 'error'
        }
      } else {
        // 注册
        if (form.password !== form.confirmPassword) {
          message.value = '两次输入的密码不一致'
          messageType.value = 'error'
          return
        }
        const response = await fetch(`${API_BASE_URL}/register`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username: form.username, email: form.email, password: form.password })
        })
        const data = await response.json()
        if (response.ok) {
          ElMessage.success('注册成功，请登录')
          isLogin.value = true
          // 跳转到登录界面
          router.push('/login')
        } else {
          message.value = data.error || '注册失败'
          messageType.value = 'error'
        }
      }
    } catch (error) {
      message.value = '网络错误，请稍后重试'
      messageType.value = 'error'
    } finally {
      loading.value = false
    }
  })
}

const toggleMode = () => {
  isLogin.value = !isLogin.value
  Object.keys(form).forEach(key => { form[key] = '' })
  message.value = ''
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-row {
  width: 100vw;
}
.login-card {
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.12);
  padding: 40px 32px 32px 32px;
  background: rgba(255,255,255,0.98);
  border: 1px solid #f0f0f0;
}
.login-header {
  text-align: center;
  margin-bottom: 18px;
}
.login-header h2 {
  margin: 12px 0 0 0;
  font-weight: 700;
  color: #409EFF;
  font-size: 26px;
  letter-spacing: 2px;
}
.login-footer {
  text-align: center;
  margin-top: 10px;
  font-size: 15px;
}
:deep(.el-input__inner::placeholder) {
  color: #bfbfbf !important;
  font-size: 15px;
}
</style> 